import logger from "@shared/logger/renderer-logger";
import type { ToolCallResult } from "@shared/types/openai";
import type { SequentialMessageContent } from "@shared/types/sequential-content";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

export function useMessageCopy() {
  const [copied, setCopied] = useState(false);
  const { t } = useTranslation("translation", { keyPrefix: "message" });

  // Utility function to extract full message content including MCP content
  const extractFullMessageContent = (
    content: string,
    toolCalls?: string | null,
    contentBlocks?: string | null,
    hasSequentialContent?: boolean | null,
  ): string => {
    const parts: string[] = [];

    // Add regular content if available
    if (content?.trim()) {
      parts.push(content);
    }

    // Handle sequential content blocks (MCP format)
    if (hasSequentialContent && contentBlocks) {
      try {
        const sequentialContent: SequentialMessageContent =
          JSON.parse(contentBlocks);
        for (const block of sequentialContent.blocks || []) {
          if (block.type === "reflection" && block.content) {
            parts.push(`**Reflection:**\n${block.content}`);
          } else if (block.type === "tool_call" && block.toolCall) {
            const toolCall = block.toolCall;
            parts.push(`**Tool Call: ${toolCall.name}**`);
            if (toolCall.arguments) {
              try {
                const args = JSON.parse(toolCall.arguments);
                parts.push(`Arguments: ${JSON.stringify(args, null, 2)}`);
              } catch {
                parts.push(`Arguments: ${toolCall.arguments}`);
              }
            }
            if (toolCall.result) {
              parts.push(`Result: ${toolCall.result}`);
            }
            if (toolCall.error) {
              parts.push(`Error: ${toolCall.error}`);
            }
          }
        }
      } catch (error) {
        logger.error("Failed to parse sequential content blocks for copy", {
          error,
        });
      }
    }
    // Handle legacy tool calls
    else if (toolCalls) {
      try {
        const toolCallResults: ToolCallResult[] = JSON.parse(toolCalls);
        for (const toolCall of toolCallResults) {
          parts.push(`**Tool Call: ${toolCall.name}**`);
          if (toolCall.arguments) {
            try {
              const args = JSON.parse(toolCall.arguments);
              parts.push(`Arguments: ${JSON.stringify(args, null, 2)}`);
            } catch {
              parts.push(`Arguments: ${toolCall.arguments}`);
            }
          }
          if (toolCall.result) {
            parts.push(`Result: ${toolCall.result}`);
          }
          if (toolCall.error) {
            parts.push(`Error: ${toolCall.error}`);
          }
        }
      } catch (error) {
        logger.error("Failed to parse tool calls for copy", { error });
      }
    }

    return parts.join("\n\n");
  };

  const handleCopy = async (content: string) => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
      toast.success(t("copy-success"));
    } catch (error) {
      logger.error("复制失败", { error });
      toast.error(t("copy-failed"));
    }
  };

  const handleCopySelected = async (savedSelection?: string) => {
    try {
      const textToCopy =
        savedSelection || window.getSelection()?.toString() || "";
      if (textToCopy) {
        await navigator.clipboard.writeText(textToCopy);
        toast.success(t("copy-success"));
      }
    } catch (error) {
      logger.error("复制选中内容失败", { error });
      toast.error(t("copy-failed"));
    }
  };

  const getSelectedText = () => {
    const selection = window.getSelection();
    return selection?.toString() || "";
  };

  return {
    copied,
    handleCopy,
    handleCopySelected,
    getSelectedText,
    extractFullMessageContent,
  };
}
